package com.family.grandapp

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import kotlin.collections.ArrayList

class MyAdapter(private var context: Context, private var data: ArrayList<ArrayList<String>>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val itemIv: AppCompatImageView = view.findViewById(R.id.item_iv)
        val itemTv: AppCompatTextView = view.findViewById(R.id.item_tv)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.app_item, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val phoneInfo = data[position]
        val applyDimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7f, context.resources.displayMetrics)
        with(holder) {
            itemIv.load(phoneInfo[2]) {
                error(R.mipmap.person)
                transformations(RoundedCornersTransformation(applyDimension))
            }
            itemTv.text = phoneInfo[0]
        }
        holder.itemView.setOnClickListener {
            //获得权限之后
            val intent = Intent()
            intent.action = Intent.ACTION_CALL
            intent.data = Uri.parse("tel:" + data[holder.adapterPosition][1])
            context.startActivity(intent)
        }
    }

    override fun getItemCount() = data.size

    @SuppressLint("NotifyDataSetChanged")
    fun setList(contactNumbers: ArrayList<ArrayList<String>>) {
        data = contactNumbers
        notifyDataSetChanged()
    }
}
